/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller;

import Entity.*;
import Model.*;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author user
 */
public class TambahPenelitian extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        HttpSession session = request.getSession();
        ArrayList listRole = new ArrayList();
//        listRole.add("tata_usaha_jurusan");
//            listRole.add("dosen");
//            listRole.add("koordinator_ppm");
        //listRole.add("koordinator_kerjasama");
        //listRole.add("mahasiswa");
//        session.setAttribute("role", listRole);
//        session.setAttribute("id_user", "0019027303");
        String idUser = (String) session.getAttribute("id_user");

        ArrayList ListRole = new ArrayList();
        ListRole = (ArrayList) session.getAttribute("role");

        boolean bukanRole = true;
        for (int i = 0; i < ListRole.size(); i++) {
            if (ListRole.get(i).equals("tata_usaha_jurusan") || ListRole.get(i).equals("dosen")) {
                bukanRole = false;
            }
        }

        if (ListRole.size() <= 0) {
            Login servlet = new Login();
            servlet.processRequest(request, response);
        } else if (bukanRole) {
            request.setAttribute("menu", "home");
            request.setAttribute("submenu", "");
            MenuUtama servlet = new MenuUtama();
            servlet.processRequest(request, response);
        } else {

            Penelitian penelitian = new Penelitian();
            DaftarPenelitian daftarPenelitian = new DaftarPenelitian();

            String status = "";
            if (request.getParameter("status") != null) {
                status = request.getParameter("status");
            }

            if (status.equals("submitData")) {
                String[] array = new String[9];

                Calendar c = Calendar.getInstance();
                c.setTime(new Date());
                //String d = + "-"+c.MONTH+"-"+c.DATE;
                int Month = c.get(Calendar.MONTH) + 1;

                String tanggal = c.get(Calendar.DATE) + "" + Month + "" + c.get(Calendar.YEAR) + "_" + c.get(Calendar.HOUR_OF_DAY) + "" + c.get(Calendar.MINUTE);

                try {
                    PrintWriter out = response.getWriter();

                    // Check that we have a file upload request

                    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

                    // Create a factory for disk-based file items  
                    DiskFileItemFactory factory = new DiskFileItemFactory();

                    // Create a new file upload handler  
                    ServletFileUpload fileUpload = new ServletFileUpload(factory);

                    // Parse the request 
                    List items = fileUpload.parseRequest(request);
                    Iterator ir = items.iterator();
                    int count = 0;
                    while (ir.hasNext()) {
                        FileItem item = (FileItem) ir.next();
                        if (item.isFormField()) {
                            //mengambil data input yang selain file
                            out.print(item.getFieldName());
                            array[count] = item.getString();
                            count++;
                        } else {
                            if (item.getFieldName().equals("sk")) {
                                String nama = tanggal + "_" + item.getName();
                                String location = "C:" + File.separator + "File" + File.separator + "Penelitian" + File.separator + "SK";
                                String uploadFile = location + File.separator + nama;
                                File file = new File(uploadFile);
                                item.write(file);

                                penelitian.setSkPenelitian(nama);
                                penelitian.setTanggalUploadSkPenelitian(c.get(Calendar.YEAR) + "-" + Month + "-" + c.get(Calendar.DATE));
                                penelitian.setTipeSkPenelitian(item.getContentType());
                                penelitian.setUkuranSkPenelitian("" + item.getSize() / 1000 + " MB");
                                //                          
                                System.out.println(nama);
                                System.out.println(item.getSize());
                                System.out.println(item.getContentType());
                            } else if (item.getFieldName().equals("lap")) {
                                String nama = tanggal + "_" + item.getName();
                                String location = "C:" + File.separator + "File" + File.separator + "Penelitian" + File.separator + "Laporan_Penelitian";
                                String uploadFile = location + File.separator + nama;
                                File file = new File(uploadFile);
                                item.write(file);

                                penelitian.setLampiranLaporan(nama);
                                penelitian.setTanggalUploadLaporan(c.get(Calendar.YEAR) + "-" + Month + "-" + c.get(Calendar.DATE));
                                penelitian.setTipeLampiranLaporan(item.getContentType());
                                penelitian.setUkuranLampiranLaporan("" + item.getSize() / 1000 + " MB");
                            }
                        }
                    }
                } catch (FileUploadException ex) {
                    log("Error encountered while parsing the request", ex);
                } catch (Exception ex) {
                    log("Error encountered while uploading file", ex);
                }

                SumberPendanaan dana = new SumberPendanaan();
                int jumlahDosen = 0;
                int jumlahMhs = 0;
                penelitian.setJudulPenelitian(array[0]);
                for (int i = 0; i < ListRole.size(); i++) {
                    if (ListRole.get(i).equals("tata_usaha_jurusan")) {
                        penelitian.setKetuaPeneliti(array[1]);
                        penelitian.setDanaDiajukan(array[2]);
                        penelitian.setDanaDiterima(array[3]);
                        dana.setIdSumberPendanaan(Integer.parseInt(array[4]));
                        penelitian.setTanggalPenelitianDimulai(array[5]);
                        penelitian.setTanggalPenelitianSelesai(array[6]);
                        jumlahDosen = Integer.parseInt(array[7]);
                        jumlahMhs = Integer.parseInt(array[8]);
                    } else {
                        penelitian.setKetuaPeneliti(idUser);
                        penelitian.setDanaDiajukan(array[1]);
                        penelitian.setDanaDiterima(array[2]);
                        dana.setIdSumberPendanaan(Integer.parseInt(array[3]));
                        penelitian.setTanggalPenelitianDimulai(array[4]);
                        penelitian.setTanggalPenelitianSelesai(array[5]);
                        jumlahDosen = Integer.parseInt(array[6]);
                        jumlahMhs = Integer.parseInt(array[7]);
                    }
                }
                User userPengupload = new User();
                userPengupload.setIdUser(idUser);
                penelitian.setPengupload(userPengupload);

                penelitian.setSumberDana(dana);

                penelitian.setUniqueKey(tanggal + Math.random());

                DosenPeneliti ketuaPeneliti = new DosenPeneliti();
                DaftarDosenPeneliti ModelDosenPeneliti = new DaftarDosenPeneliti();

                User user = new User();
                user.setIdUser(penelitian.getKetuaPeneliti());

                Dosen dosen = new Dosen();
                dosen.setUser(user);

                ketuaPeneliti.setStatusDosen("1");
                ketuaPeneliti.setPenelitian(penelitian);
                ketuaPeneliti.setDosen(dosen);

                session.setAttribute("penelitian", penelitian);
                session.setAttribute("ketuaPeneliti", ketuaPeneliti);
                session.setAttribute("jumlahDosen", jumlahDosen);
                session.setAttribute("jumlahMhs", jumlahMhs);

                DosenModel dosenModel = new DosenModel();
                List<Dosen> listDosen = new ArrayList<Dosen>();
                listDosen = dosenModel.DaftarDosen();

                request.setAttribute("dosen", listDosen);
                request.setAttribute("menu", "ppm");
                request.setAttribute("submenu", "penelitian");

                RequestDispatcher dis = request.getRequestDispatcher("ppm/halamanDosenPeneliti.jsp");
                dis.forward(request, response);

            } else if (status.equals("submitDosen")) {

                int jumlahDosen = Integer.parseInt((String) ""+session.getAttribute("jumlahDosen"));
                DosenPeneliti[] listDosenPeneliti = new DosenPeneliti[jumlahDosen];
                penelitian = (Penelitian) session.getAttribute("penelitian");
                
                for (int i = 1; i <= jumlahDosen; i++) {
                    String idDosen = request.getParameter("dosen[" + i + "]");
                    System.out.println("HEHEHE"+idDosen);
                    User user = new User();
                    user.setIdUser(idDosen);

                    Dosen dosen = new Dosen();
                    dosen.setUser(user);

                    DosenPeneliti dosenPeneliti = new DosenPeneliti();
                    dosenPeneliti.setPenelitian(penelitian);
                    dosenPeneliti.setStatusDosen("0");
                    dosenPeneliti.setDosen(dosen);
                    listDosenPeneliti[i - 1] = dosenPeneliti;
                }

                session.setAttribute("listDosenPeneliti", listDosenPeneliti);

                request.setAttribute("menu", "ppm");
                request.setAttribute("submenu", "penelitian");

                RequestDispatcher dis = request.getRequestDispatcher("ppm/halamanMhsPenelitian.jsp");
                dis.forward(request, response);

            } else if (status.equals("submitMhs")) {
                
                int jumlahMhs = Integer.parseInt((String) ""+session.getAttribute("jumlahMhs"));
                MahasiswaPeneliti[] listMahasiswaPeneliti = new MahasiswaPeneliti[jumlahMhs];
                MahasiswaPeneliti mhsPeneliti = new MahasiswaPeneliti();
                penelitian = (Penelitian) session.getAttribute("penelitian");
                
                for (int i = 1; i <= jumlahMhs; i++) {
                    String namaMhs = request.getParameter("nama[" + i + "]");
                    String nrpMhs = request.getParameter("nrp[" + i + "]");
                    String judulTgsAkhir = request.getParameter("judul[" + i + "]");
                    
                    mhsPeneliti.setJudulTugasAkhir(judulTgsAkhir);
                    mhsPeneliti.setNamaMahasiswa(namaMhs);
                    mhsPeneliti.setNrpMahasiswa(nrpMhs);
                    mhsPeneliti.setPenelitian(penelitian);
                    
                    listMahasiswaPeneliti[i - 1] = mhsPeneliti;
                    System.out.println("id"+listMahasiswaPeneliti[i-1].getNrpMahasiswa()+"--iii"+listMahasiswaPeneliti[i-1].getPenelitian().getUniqueKey());
                }
                
                boolean sukses = daftarPenelitian.tambahDataPenelitian(penelitian);
                
                String pesan;
                String isiPesan;
                
                if(sukses){     
                    DosenPeneliti ketuaPeneliti = new DosenPeneliti();
                    DaftarDosenPeneliti ModelDosenPeneliti = new DaftarDosenPeneliti();
                    ketuaPeneliti = (DosenPeneliti) session.getAttribute("ketuaPeneliti");

                    boolean hasil = ModelDosenPeneliti.tambahTimDosenPPM(ketuaPeneliti);
                    
                    int jumlahDosen = Integer.parseInt((String) ""+session.getAttribute("jumlahDosen"));
                    DosenPeneliti[] listDosenPeneliti = new DosenPeneliti[jumlahDosen];
                    listDosenPeneliti = (DosenPeneliti[]) session.getAttribute("listDosenPeneliti");
                    
                    System.out.println("HTYYUYUYUUY"+listDosenPeneliti.length);
                    
                    DaftarMahasiswaPeneliti modelMahasiswaPeneliti = new DaftarMahasiswaPeneliti();
                    
                    for(int i =0; i < jumlahDosen; i++){
                            DaftarDosenPeneliti ModelDosenPeneliti1 = new DaftarDosenPeneliti();
    //                        System.out.println("tetrtrtr"+listDosenPeneliti[i].getDosen().getUser().getIdUser());
    //                        System.out.println("dsfsf"+listDosenPeneliti[i].getStatusDosen());
    //                        System.out.println("dsfsf"+listDosenPeneliti[i].getPenelitian().getUniqueKey());
                            boolean hasil1 =  ModelDosenPeneliti1.tambahTimDosenPPM(listDosenPeneliti[i]);
                        }

                   for (int i = 1; i <= jumlahMhs; i++) {
                        String namaMhs = request.getParameter("nama[" + i + "]");
                        String nrpMhs = request.getParameter("nrp[" + i + "]");
                        String judulTgsAkhir = request.getParameter("judul[" + i + "]");

                        mhsPeneliti.setJudulTugasAkhir(judulTgsAkhir);
                        mhsPeneliti.setNamaMahasiswa(namaMhs);
                        mhsPeneliti.setNrpMahasiswa(nrpMhs);
                        mhsPeneliti.setPenelitian(penelitian);

                        boolean hasil2 = modelMahasiswaPeneliti.tambahTimMahasiswaPeneliti(mhsPeneliti);
                    }
//                    for(int j =0; j < jumlahMhs; j++){
//                        DaftarMahasiswaPeneliti modelMahasiswaPeneliti = new DaftarMahasiswaPeneliti();
//                        System.out.println("idf"+listMahasiswaPeneliti[j].getNrpMahasiswa());
//                        boolean hasil2 = modelMahasiswaPeneliti.tambahTimMahasiswaPeneliti(listMahasiswaPeneliti[j]);
//                    }
                
                    pesan = "sukses";
                    isiPesan = "Data penelitian berhasil ditambahkan";
                } else {
                    pesan = "gagal";
                    isiPesan = "Data penelitian tidak berhasil ditambahkan";
                }
//                session.setAttribute("pesan", pesan);
//                session.setAttribute("isiPesan", isiPesan);

                request.setAttribute("pesan", pesan);
                request.setAttribute("isiPesan", isiPesan);
                TampilDaftarPenelitian servlet = new TampilDaftarPenelitian();
                servlet.processRequest(request, response);

            } else if (status.equals("batal")) {

                session.removeAttribute("penelitian");
                session.removeAttribute("ketuaPeneliti");
                session.removeAttribute("jumlahDosen");
                session.removeAttribute("jumlahMhs");
                session.removeAttribute("listDosenPeneliti");
                
                List<HasilLaporanPpm> listHasil = new ArrayList<HasilLaporanPpm>();
                HasilLaporanPpm hasil = new HasilLaporanPpm();

                listHasil = hasil.ambilDaftarHasilLaporanPpm();

                List<SumberPendanaan> listSumberDana = new ArrayList<SumberPendanaan>();
                DaftarSumberPendanaan modelSumberPendanaan = new DaftarSumberPendanaan();

                listSumberDana = modelSumberPendanaan.ambilDaftarSumberDana("Penelitian");

                List<Dosen> listDosen = new ArrayList();
                DosenModel dosenModel = new DosenModel();

                listDosen = dosenModel.DaftarDosen();

                request.setAttribute("hasil", listHasil);
                request.setAttribute("dana", listSumberDana);
                request.setAttribute("dosen", listDosen);
                request.setAttribute("menu", "ppm");
                request.setAttribute("submenu", "penelitian");

                RequestDispatcher dis = request.getRequestDispatcher("ppm/halamanTambahPenelitian.jsp");
                dis.forward(request, response);
            } else {
                
                session.removeAttribute("penelitian");
                session.removeAttribute("ketuaPeneliti");
                session.removeAttribute("jumlahDosen");
                session.removeAttribute("jumlahMhs");
                session.removeAttribute("listDosenPeneliti");
                
                List<HasilLaporanPpm> listHasil = new ArrayList<HasilLaporanPpm>();
                HasilLaporanPpm hasil = new HasilLaporanPpm();

                listHasil = hasil.ambilDaftarHasilLaporanPpm();

                List<SumberPendanaan> listSumberDana = new ArrayList<SumberPendanaan>();
                DaftarSumberPendanaan modelSumberPendanaan = new DaftarSumberPendanaan();

                listSumberDana = modelSumberPendanaan.ambilDaftarSumberDana("Penelitian");

                List<Dosen> listDosen = new ArrayList();
                DosenModel dosenModel = new DosenModel();

                listDosen = dosenModel.DaftarDosen();

                request.setAttribute("hasil", listHasil);
                request.setAttribute("dana", listSumberDana);
                request.setAttribute("dosen", listDosen);
                request.setAttribute("menu", "ppm");
                request.setAttribute("submenu", "penelitian");

                RequestDispatcher dis = request.getRequestDispatcher("ppm/halamanTambahPenelitian.jsp");
                dis.forward(request, response);
            }
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
